package com.gduf.lsm.service;

import cn.hutool.core.util.ObjectUtil;
import com.gduf.lsm.common.enums.ResultCodeEnum;
import com.gduf.lsm.entity.News;
import com.gduf.lsm.exception.CustomException;
import com.gduf.lsm.mapper.NewsMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author lsm
 * @Data
 * 咨询信息
 */
@Service
public class NewsService {
    @Autowired
    private NewsMapper newsMapper;

    /**
     * 新增
     * @param news
     */
    public void add(News news) {
        //判断咨询标题是否重复
        if(news.getTitle()==null){
            throw new CustomException(ResultCodeEnum.NEWS_NULL_ERROR);
        }
        //根据标题查询是否重复
        News dbNews = newsMapper.selectByTitle(news.getTitle());
        //判断咨询信息是否存在
        if (ObjectUtil.isNotNull(dbNews)) {
            throw new CustomException(ResultCodeEnum.NEWS_EXIST_ERROR);
        }
        newsMapper.insert(news);
    }

    /**
     * 删除单个
     * @param id
     */
    public void deleteById(Integer id) {
        newsMapper.deleteById(id);
    }

    /**
     * 批量删除
     * @param ids
     */
    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            newsMapper.deleteById(id);
        }
    }

    /**
     * 修改
     * @param news
     */
    public void updateById(News news) {
        newsMapper.updateById(news);
    }

    /**
     * 根据ID查询
     * @param id
     * @return
     */
    public News selectById(Integer id) {
        return newsMapper.selectById(id);
    }

    /**
     * 查询所有
     * @param news
     * @return
     */
    public List<News> selectAll(News news) {
        return newsMapper.selectAll(news);
    }

    /**
     * 分页查询
     * @param news
     * @param pageNum
     * @param pageSize
     * @return
     */
    public PageInfo<News> selectPage(News news, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<News> list = newsMapper.selectAll(news);
        return PageInfo.of(list);
    }

    /**
     * 按最新最热条件查找数据
     * @param sort
     * @return
     */
    public List<News> selectTopNews(String sort) {
        return newsMapper.selectTopNews(sort);
    }

    /**
     * 更新浏览量
     * @param id
     */
    public void updateCount(Integer id) {
        newsMapper.updateCount(id);
    }
}
